package com.lagou.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.lagou.entity.ResponseDTO;
import com.lagou.entity.User;
import com.lagou.entity.UserDTO;
import com.lagou.service.UserService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class UserController {
    @Reference
    private UserService userService;

    @RequestMapping("login")
    public UserDTO login(String phone, String password) {
        UserDTO dto = new UserDTO();
        System.out.println("phone = " + phone);
        System.out.println("password = " + password);

        //检测手机号是否注册
        Integer i = userService.checkPhone(phone);
        if (i == 0) {
            //注册
            userService.register(phone, password);
        }

        //登录
        User user = userService.login(phone, password);
        if (user != null) {
            dto.setState(200);
            dto.setMessage(i == 0 ? "手机号尚未注册，系统已帮您自动注册并登录，请牢记密码！" : "登录成功！");
        } else {
            dto.setState(500);
            dto.setMessage("账号密码不匹配，登录失败！");
        }
        dto.setContent(user);

        return dto;
    }

    @PostMapping("updateUserInfo")
    public ResponseDTO updateUserInfo(String userid, String portrait, String name) {
        ResponseDTO resp = new ResponseDTO(true, 200, "修改成功");
        if (userService.updateUserInfo(userid, portrait, name) != 1) {
            resp.setSuccess(false);
            resp.setState(500);
            resp.setMessage("修改失败");
        }

        return resp;
    }

    @PostMapping("updatePassword")
    public ResponseDTO updatePassword(String userid, String password) {
        ResponseDTO resp = new ResponseDTO(true, 200, "修改成功");
        if (userService.updatePassword(userid, password) != 1) {
            resp.setSuccess(false);
            resp.setState(500);
            resp.setMessage("修改失败");
        }

        return resp;
    }
}
